package main.observer.pattern.demo;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by DELL
 * Date: 2019/9/27.
 * Time: 8:22
 */

class Observer {
    public void update(){
        System.out.println("flge value changed in subject");
    }
}

interface ISubject {
    void register(Observer observer);
    void unregister(Observer observer);
    void notifyObservers();
}

class Subject implements ISubject {
    List<Observer> observerList = new ArrayList<Observer>();
    private int flag;


    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
        notifyObservers();
    }

    @Override
    public void register(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void unregister(Observer observer) {
        observerList.remove(observer);
    }



    @Override
    public void notifyObservers() {
        for (int i = 0; i < observerList.size() ; i++) {
            observerList.get(i).update();
        }
    }
}

class ObserverPatternEx {
    public static void main(String[] args) {

        System.out.println("***Observer Pattern Demo***\n");
        Observer observer1 = new Observer();
        Subject subject1 = new Subject();
        subject1.register(observer1);
        System.out.println("setting flag equal 5");
        subject1.setFlag(5);
        System.out.println("setting flag equal 25");
        subject1.setFlag(25);
       //no notification this time to o1 .since it is
        subject1.unregister(observer1);
        System.out.println("setting flag equal 50");
        subject1.setFlag(50);



    }

}

